package cc.git.liuyan;

import com.sun.tools.attach.*;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

public class AgentMain {
    private static List<String> notNeedHandleJarNamePrefix = new ArrayList<String>();

    static {
        notNeedHandleJarNamePrefix.add("com.intellij");
        notNeedHandleJarNamePrefix.add("org.jetbrains");
        notNeedHandleJarNamePrefix.add("cc.git.liuyan.AgentMain");
        notNeedHandleJarNamePrefix.add("agent-main-1.0.0");
        notNeedHandleJarNamePrefix.add("localUseAgentMain");
    }

    //    暂不做动态Agent处理，请不要使用(虽然现在可以使用，但有问题)
    public static void main(String[] args) throws IOException, AttachNotSupportedException, AgentLoadException, AgentInitializationException {
        File agentFile = new File("./localUseAgent.jar");
        if (!agentFile.exists()) {
            SelfLog.info(String.format("路径%s下缺少localUseAgent.jar，无法启动", agentFile.getAbsolutePath()));
            return;
        }

        List<VirtualMachineDescriptor> runingJarList = VirtualMachine.list();
        SelfLog.info(String.format("JAVA进程如下："));
        List<String> canUsePids = new ArrayList<>();
        Map<String, String> pidNameMap = new HashMap<>();
        for (VirtualMachineDescriptor runingJar : runingJarList) {
            if (runingJar.displayName() == null || runingJar.displayName().trim().isEmpty() || notNeedHandle(runingJar.displayName())) {
                continue;
            }
            SelfLog.info(String.format("PID：%s  -> JARNAME：%s", runingJar.id(), runingJar.displayName()));
            canUsePids.add(runingJar.id());
            pidNameMap.put(runingJar.id(), runingJar.displayName());
        }
        SelfLog.info("请输入要处理的PID，输入完后回车确认！");
        Scanner scanner = new Scanner(System.in);
        String pid = scanner.nextLine();
        while (!canUsePids.contains(pid)) {
            SelfLog.info("PID：" + pid + " 不存在，请输入正确的PID！");
            pid = scanner.nextLine();
        }
        SelfLog.info("选择了PID：" + pid);

        VirtualMachine vm = VirtualMachine.attach(pid);
        try {
            vm.loadAgent(agentFile.getAbsolutePath(), pidNameMap.get(pid));
        } finally {
            vm.detach();
        }
    }

    private static boolean notNeedHandle(String jarName) {
        if (jarName == null || notNeedHandleJarNamePrefix.stream().anyMatch(jarName::startsWith)) {
            return true;
        }
        return false;
    }
}